package com.example.demo.controller.admin;

import com.example.demo.Application;
import com.example.demo.enums.BusinessEnum;
import com.example.demo.exception.BusinessException;
import com.example.demo.model.Json;
import com.example.demo.utils.FileNameUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/back/upload")
public class UploadController {

    protected boolean isJarMode = false;

    protected String domain = "https://storage.1088web.com";

    @RequestMapping("image")
    Json image(@RequestParam("image") MultipartFile file)
    {
        try{
            // 以 jar 的方式运行
            if (Application.class.getResource("").getProtocol().equals("jar")) {
                isJarMode = true;
            }

            if(file.isEmpty()){
                throw new BusinessException(BusinessEnum.FILE_EMPTY_ERROR);
            }

            //获取jar包所在目录
            ApplicationHome h = new ApplicationHome(getClass());
            File jarF = h.getSource();
            String savePath = "/static/upload/images/";
            //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
            String uploadPath = jarF.getParentFile().toString() + (isJarMode ? "" : "/classes") + savePath;

            // 如果文件夹不存在则创建保存文件的文件夹
            File dir = new File(uploadPath);
            if (! dir.exists()) {
                dir.mkdirs();
            }

            // 设置文件名称
            String filenameup = FileNameUtil.getFileName(file.getOriginalFilename());
            // 设置存储路径和文件名称
            File dest = new File(uploadPath, filenameup);

            // 保存文件
            try {
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                // 抛出异常
                throw new BusinessException(BusinessEnum.FILE_STATE_ERROR_OR_EXITES);
            } catch (IOException e) {
                // 抛出异常
                throw new BusinessException(BusinessEnum.FILE_MOVE_FAILED);
            }

            Map<String, String> result = new HashMap<>();
            result.put("url", domain + savePath + filenameup);

            return new Json().success(result, "success");
        }catch (BusinessException e)
        {
            return new Json().error(e.getMessage(), e.getCode());
        }
    }
}
